# -*- coding:utf-8 -*-
# @Time: 2020/8/24 15:38
# @Author: liupengfei
# @File: serializers.py


from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import get_user_model, authenticate
from rest_framework_jwt.settings import api_settings
from apps.member.models import Member

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class UserJWTSerializer(JSONWebTokenSerializer):
    '''登录token获取'''

    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                payload = jwt_payload_handler(user)

                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username

                }
        msg = '账号密码错误！'
        raise serializers.ValidationError(msg)


class UserJwtSerializer(serializers.ModelSerializer):
    '''刷新token返回的数据'''

    class Meta:
        model = User
        fields = ('username', 'nickname', 'is_staff')


class AccountSerializer(serializers.ModelSerializer):
    '''后台管理CRUD操作'''

    class Meta:
        model = User
        fields = ('id', 'is_superuser', 'username', 'nickname', 'is_active', 'is_staff')


class MemberSerializer(serializers.ModelSerializer):
    '''后台MemberCRUD操作'''
    username = serializers.CharField(source='user.username', read_only=True)
    nickname = serializers.CharField(source='user.nickname', read_only=True)
    gender = serializers.CharField(source='get_gender_display', read_only=True)
    is_active = serializers.CharField(source='user.is_active', read_only=True)
    identity_text = serializers.CharField(source='get_identity_display', read_only=True)

    class Meta:
        model = Member
        fields = ('face_url', 'gender', 'province', 'city', 'username', 'nickname',
                  'is_active', 'identity_text', 'identity', 'id')
